package com.atgugu.flink.chapter09;

import com.atgugu.flink.bean.WaterSensor;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.cep.CEP;
import org.apache.flink.cep.PatternFlatSelectFunction;
import org.apache.flink.cep.PatternFlatTimeoutFunction;
import org.apache.flink.cep.PatternStream;
import org.apache.flink.cep.pattern.Pattern;
import org.apache.flink.cep.pattern.conditions.SimpleCondition;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.time.Duration;
import java.util.List;
import java.util.Map;

/**
 * @Author lzc
 * @Date 2022/4/9 8:57
 */
public class Flink12_CEP_Flat {
    
    
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        
        /*
            sensor_1,1,10
            sensor_1,2,20
            sensor_1,3,30
            sensor_2,4,30
            sensor_1,4,400
            sensor_2,5,50
            sensor_2,6,60

         */
        
        // 1. 先有一个流
        SingleOutputStreamOperator<WaterSensor> stream = env
            .fromElements(
                new WaterSensor("sensor_1", 1000L, 1),
                new WaterSensor("sensor_2", 2000L, 2),
                new WaterSensor("sensor_1", 3000L, 5),
                new WaterSensor("sensor_2", 5000L, 5),
                new WaterSensor("sensor_2", 7000L, 5),
                new WaterSensor("sensor_1", 8000L, 6)
            )
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((ws, ts) -> ws.getTs())
            );
        
        // 2. 定制模式(指定规则)
        Pattern<WaterSensor, WaterSensor> pattern = Pattern
            .<WaterSensor>begin("s1")
            .where(new SimpleCondition<WaterSensor>() {
                @Override
                public boolean filter(WaterSensor value) throws Exception {
                    return "sensor_1".equals(value.getId());
                }
            })
            .next("s2")
            .where(new SimpleCondition<WaterSensor>() {
                @Override
                public boolean filter(WaterSensor value) throws Exception {
                    return "sensor_2".equals(value.getId());
                }
            })
            .within(Time.seconds(2));
        
        
        // 3. 把模式作用到流上, 得到一个模式流
        PatternStream<WaterSensor> ps = CEP.pattern(stream, pattern);
        // 4. 从模式流取出匹配到的数据
        /*ps
            .flatSelect(new PatternFlatSelectFunction<WaterSensor, WaterSensor>() {
                @Override
                public void flatSelect(Map<String, List<WaterSensor>> pattern,
                                       Collector<WaterSensor> out) throws Exception {
                    for (Map.Entry<String, List<WaterSensor>> entry : pattern.entrySet()) {
                        List<WaterSensor> list = entry.getValue();
                        for (WaterSensor waterSensor : list) {
                            out.collect(waterSensor);
                            
                        }
                    }
                }
            })
            .print();*/
    
        SingleOutputStreamOperator<WaterSensor> normal = ps
            .flatSelect(
                new OutputTag<WaterSensor>("timeout") {},
                new PatternFlatTimeoutFunction<WaterSensor, WaterSensor>() {
                    @Override
                    public void timeout(Map<String, List<WaterSensor>> pattern,
                                        long timeoutTimestamp,
                                        Collector<WaterSensor> out) throws Exception {
                        for (Map.Entry<String, List<WaterSensor>> entry : pattern.entrySet()) {
                            List<WaterSensor> list = entry.getValue();
                            for (WaterSensor waterSensor : list) {
                                out.collect(waterSensor);
                            
                            }
                        }
                    }
                },
            
                new PatternFlatSelectFunction<WaterSensor, WaterSensor>() {
                    @Override
                    public void flatSelect(Map<String, List<WaterSensor>> pattern,
                                           Collector<WaterSensor> out) throws Exception {
                        for (Map.Entry<String, List<WaterSensor>> entry : pattern.entrySet()) {
                            List<WaterSensor> list = entry.getValue();
                            for (WaterSensor waterSensor : list) {
                                out.collect(waterSensor);
                            
                            }
                        }
                    }
                }
            );
        normal.print("normal");
        normal.getSideOutput(new OutputTag<WaterSensor>("timeout") {}).print("timeout");
    
    
        try {
            env.execute();
        } catch (
            Exception e) {
            e.printStackTrace();
        }
        
    }
    
    
}
/*
cep有三种数据:
1 匹配上的数据  可以得到
2. 没有匹配上的  无法获取
3. 超时数据 可以得到  会放入到测输出流中
 */
